package net.gz01.wallet.web.interceptors;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import net.gz01.wallet.common.LayuiRespon;
import net.gz01.wallet.web.model.AdminUser;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.OrgUser;

/**
 * 全局拦截器,主要记录操作日志,登录超时验证
 *
 * @author 钟展峰
 *
 *         2015年8月25日
 */
public class SessionTimeOutInterceptor implements Interceptor {

	private static final String ADMIN_ACTION = "/admin";
	private static final String ORG_ACTION = "/org";
	private static final String MERCH_ACTION = "/customer";

	@Override
	public void intercept(Invocation inv) {
		Controller ctr = inv.getController();
		String actionKey = inv.getActionKey();

		if (actionKey.startsWith(ADMIN_ACTION)) {
			processAdmin(inv, ctr);
		} else if (actionKey.startsWith(ORG_ACTION)) {
			processOrg(inv, ctr);
		} else if (actionKey.startsWith(MERCH_ACTION)) {
			processMerch(inv, ctr);
		}else if(actionKey.startsWith("help")){

		}

	}

	private void processAdmin(Invocation inv, Controller ctr) {
		AdminUser loginUser = (AdminUser) ctr.getSession().getAttribute("loginAdminUser");
		if (loginUser != null) {
			inv.invoke();
			return;
		}
		if (isAjaxRequest(ctr.getRequest())) {
			ctr.renderJson(LayuiRespon.getTimeOut());
		} else {
			ctr.redirect("/admin/loginpage");
		}
	}

	private void processOrg(Invocation inv, Controller ctr) {
		OrgUser loginUser = (OrgUser) ctr.getSession().getAttribute("loginOrgUser");
		if (loginUser != null) {
			inv.invoke();
			return;
		}
		if (isAjaxRequest(ctr.getRequest())) {
			ctr.renderJson(LayuiRespon.getTimeOut());
		} else {
			ctr.redirect("/org/loginpage");
		}
	}

	private void processMerch(Invocation inv, Controller ctr) {
		MerchUser loginMerchUser = (MerchUser) ctr.getSession().getAttribute(MerchUser.SessionKey);
		if (loginMerchUser != null) {
			inv.invoke();
			return;
		}
		if (isAjaxRequest(ctr.getRequest())) {
			ctr.renderJson(LayuiRespon.getTimeOut());
		} else {
			ctr.redirect("/customer/login");
		}
	}

	private boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader("X-Requested-With");
		return ("XMLHttpRequest").equals(requestType);
	}
}
